package com.shu.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ssm
 * @version V1.0
 * @description:
 * @date 2020/7/31 10:15
 */
@Slf4j
public class ConditionTest {
    private ReentrantLock lock  = new ReentrantLock();
    private Condition condition  = lock.newCondition();

    void method1() throws InterruptedException {
        try {
            lock.lock();
            log.info("{}",Thread.currentThread().getName() + "条件不满足,开始await");
            condition.await();
            log.info("{}",Thread.currentThread().getName() + "条件满足,开始执行");
        } finally {
            log.info("释放锁之前休眠1秒");
            Thread.sleep(1000);
            lock.unlock();
            log.info("锁已释放");
        }
    }


    void method2() throws InterruptedException {
        try {
            lock.lock();
            log.info("{}",Thread.currentThread().getName() + "准备1秒!");
            Thread.sleep(1000);
            log.info("{}",Thread.currentThread().getName() + "准备唤醒其他线程!");
            condition.signal();
        } finally {
            log.info("释放锁之前休眠1秒");
            Thread.sleep(1000);
            lock.unlock();
            log.info("锁已释放");
        }
    }


    public static void main(String[] args) throws InterruptedException {
        ConditionTest conditionTest = new ConditionTest();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    conditionTest.method2();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        conditionTest.method1();
    }


}
